/**
 * 粒子背景效果
 * 为登录页面创建随鼠标移动变化的粒子效果
 */

class ParticleBackground {
    constructor(options = {}) {
        this.options = {
            selector: '.login-container',
            particleCount: 80,
            connectDistance: 120,
            moveSpeed: 0.6,
            responsive: [
                {
                    breakpoint: 768,
                    options: {
                        particleCount: 40,
                        connectDistance: 80
                    }
                }
            ],
            colors: ['#8cdbff', '#7adb89', '#5bc4b8'],
            minSize: 1,
            maxSize: 3,
            ...options
        };
        
        this.particles = [];
        this.mouse = { x: 0, y: 0, radius: 100 };
        this.isAnimating = false;
        this.container = null;
        this.canvas = null;
        this.ctx = null;
        this.containerWidth = 0;
        this.containerHeight = 0;
        this.dpr = window.devicePixelRatio || 1;
        
        this.init();
    }
    
    init() {
        // 创建canvas元素
        this.container = document.querySelector(this.options.selector);
        if (!this.container) return;
        
        this.canvas = document.createElement('canvas');
        this.ctx = this.canvas.getContext('2d');
        
        // 设置样式并添加到容器
        this.canvas.classList.add('particles-canvas');
        Object.assign(this.canvas.style, {
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            pointerEvents: 'none',
            zIndex: 0
        });
        
        // 确保容器定位正确
        if (getComputedStyle(this.container).position === 'static') {
            this.container.style.position = 'relative';
        }
        
        this.container.insertBefore(this.canvas, this.container.firstChild);
        
        // 设置画布大小
        this.resizeCanvas();
        
        // 创建粒子
        this.createParticles();
        
        // 事件监听
        window.addEventListener('resize', this.resizeCanvas.bind(this));
        window.addEventListener('mousemove', this.handleMouseMove.bind(this));
        window.addEventListener('touchmove', this.handleTouchMove.bind(this), { passive: true });
        
        // 开始动画
        this.animate();
    }
    
    // 根据屏幕大小调整粒子数量
    getResponsiveOptions() {
        const width = window.innerWidth;
        let currentOptions = { ...this.options };
        
        if (this.options.responsive) {
            this.options.responsive.forEach(item => {
                if (width <= item.breakpoint) {
                    currentOptions = { ...currentOptions, ...item.options };
                }
            });
        }
        
        return currentOptions;
    }
    
    // 调整画布大小
    resizeCanvas() {
        const { width, height } = this.container.getBoundingClientRect();
        
        this.containerWidth = width;
        this.containerHeight = height;
        
        // 设置实际渲染大小
        this.canvas.width = width * this.dpr;
        this.canvas.height = height * this.dpr;
        
        // 缩放上下文以匹配DPR
        this.ctx.scale(this.dpr, this.dpr);
        
        // 如果粒子已创建，需要重新调整粒子数量
        if (this.particles.length > 0) {
            this.createParticles();
        }
    }
    
    // 创建粒子
    createParticles() {
        const options = this.getResponsiveOptions();
        this.particles = [];
        
        for (let i = 0; i < options.particleCount; i++) {
            this.particles.push({
                x: Math.random() * this.containerWidth,
                y: Math.random() * this.containerHeight,
                size: Math.random() * (options.maxSize - options.minSize) + options.minSize,
                color: options.colors[Math.floor(Math.random() * options.colors.length)],
                speedX: (Math.random() - 0.5) * options.moveSpeed,
                speedY: (Math.random() - 0.5) * options.moveSpeed
            });
        }
    }
    
    // 处理鼠标移动
    handleMouseMove(event) {
        const rect = this.canvas.getBoundingClientRect();
        this.mouse.x = event.clientX - rect.left;
        this.mouse.y = event.clientY - rect.top;
    }
    
    // 处理触摸移动
    handleTouchMove(event) {
        if (event.touches.length > 0) {
            const rect = this.canvas.getBoundingClientRect();
            this.mouse.x = event.touches[0].clientX - rect.left;
            this.mouse.y = event.touches[0].clientY - rect.top;
        }
    }
    
    // 绘制单个粒子
    drawParticle(particle) {
        this.ctx.beginPath();
        this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
        this.ctx.fillStyle = particle.color;
        this.ctx.fill();
    }
    
    // 绘制粒子之间的连接线
    drawConnections() {
        const options = this.getResponsiveOptions();
        for (let i = 0; i < this.particles.length; i++) {
            for (let j = i + 1; j < this.particles.length; j++) {
                const dx = this.particles[i].x - this.particles[j].x;
                const dy = this.particles[i].y - this.particles[j].y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance < options.connectDistance) {
                    // 根据距离计算透明度
                    const opacity = 1 - (distance / options.connectDistance);
                    
                    this.ctx.beginPath();
                    this.ctx.moveTo(this.particles[i].x, this.particles[i].y);
                    this.ctx.lineTo(this.particles[j].x, this.particles[j].y);
                    this.ctx.strokeStyle = `rgba(125, 190, 160, ${opacity * 0.5})`;
                    this.ctx.lineWidth = 0.5;
                    this.ctx.stroke();
                }
            }
        }
    }
    
    // 更新粒子位置
    updateParticles() {
        const options = this.getResponsiveOptions();
        
        for (let i = 0; i < this.particles.length; i++) {
            const particle = this.particles[i];
            
            // 更新位置
            particle.x += particle.speedX;
            particle.y += particle.speedY;
            
            // 边界检查
            if (particle.x < 0 || particle.x > this.containerWidth) {
                particle.speedX = -particle.speedX;
            }
            if (particle.y < 0 || particle.y > this.containerHeight) {
                particle.speedY = -particle.speedY;
            }
            
            // 鼠标交互：鼠标附近的粒子加速
            const dx = this.mouse.x - particle.x;
            const dy = this.mouse.y - particle.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance < this.mouse.radius) {
                // 计算排斥力度
                const force = (this.mouse.radius - distance) / this.mouse.radius;
                const directionX = dx / distance;
                const directionY = dy / distance;
                
                // 应用排斥力，远离鼠标
                particle.speedX -= directionX * force * 0.15;
                particle.speedY -= directionY * force * 0.15;
            }
            
            // 限制最大速度
            const maxSpeed = 1.2;  // 降低最大速度限制
            const speed = Math.sqrt(particle.speedX * particle.speedX + particle.speedY * particle.speedY);
            if (speed > maxSpeed) {
                particle.speedX = (particle.speedX / speed) * maxSpeed;
                particle.speedY = (particle.speedY / speed) * maxSpeed;
            }
        }
    }
    
    // 动画循环
    animate() {
        if (!this.isAnimating) {
            this.isAnimating = true;
            this.render();
        }
    }
    
    // 渲染函数
    render() {
        // 清除画布
        this.ctx.clearRect(0, 0, this.containerWidth, this.containerHeight);
        
        // 更新和绘制粒子
        this.updateParticles();
        this.drawConnections();
        
        for (const particle of this.particles) {
            this.drawParticle(particle);
        }
        
        requestAnimationFrame(this.render.bind(this));
    }
}

// 页面加载完成后初始化粒子背景
document.addEventListener('DOMContentLoaded', () => {
    new ParticleBackground({
        // 可以在这里覆盖默认选项
    });
}); 